<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 秒杀接口
 */
class FlashSale extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\FlashSale();

    }


    /**
     * 查看
     */
    public function index()
    {
        $this->limitFields = 'id,title,price,buy_num,goods_id,goods_num,is_end';

        list($where, $sort, $order, $offset, $limit , $field) = $this->buildparams();

        $total = $this->model
            ->with('goods')
            ->where($where)
            ->where(function($query) use ($where){
                $query->where('status',1);
                $query->where('is_end',0);
            })
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->with('goods')
            ->field($field)
            ->where($where)
            ->where(function($query) use ($where){
                $query->where('status',1);
                $query->where('is_end',0);
            })
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $data = [];
        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        foreach($list as $k => $v){
            $data[$k] = $v;
            $key = "flash_sale_notice_uid-" . $this->auth->id . '-' .$v['goods_id'];
            $is_notice = $client->hlen($key);
            $data[$k]['is_notice'] = $is_notice;
        }

        $result = array("total" => $total, "rows" => $data);

        $this->success('',$result);
    }


    /**
     * 详情
     */
    public function detail($goods_id = NULL)
    {
        \app\common\model\Goods::addzuji($goods_id,$this->auth->id);

        $row = \app\common\model\Goods::get($goods_id);
        if (!$row)
            $this->error(__('No Results were found'));

        $goodsAttrData = Db::name('goods_attr')->alias('ga')
            ->join('attr a', 'ga.attr_id = a.id', 'LEFT')
            ->where(['goods_id' => $goods_id])
            ->field('a.name')
            ->find();
        $row['attrName'] = $goodsAttrData['name'];

        $goodsAttrM = model('common/goodsAttr');
        $goodsAttr = $goodsAttrM->field('id,attr_value')->where(['goods_id' => $goods_id])->select();

        $row['goodsAttr'] = $goodsAttr;
        $row['type'] = \app\common\model\Goods::getType();


        if ($row['prom_type'] == 2) {
            $row['type'] = [
                ['id' => '0', 'name' => '自己买'],
                ['id' => '1', 'name' => '送一人']
            ];
        }

        $goodsPromFactory = new \app\common\logic\GoodsPromFactory();
        if (!empty($row['prom_id']) && $goodsPromFactory->checkPromType($row['prom_type'])) {
            $goodsPromLogic = $goodsPromFactory->makeModule($row);//这里会自动更新商品活动状态，所以商品需要重新查询
            $row = $goodsPromLogic->getGoodsInfo();//上面更新商品信息后需要查询

            $ActivityGoodsInfo = $goodsPromLogic->getActivityGoodsInfo();

            if (isset($ActivityGoodsInfo['item_id']) && $ActivityGoodsInfo['item_id']) {
                $ActivityGoodsInfo['goodsAttr'] = $goodsAttrM->field(['id,attr_value'])->where(['id' => $ActivityGoodsInfo['item_id']])->select();
            }

            $ActivityGoodsInfo['shengyu_count'] = $ActivityGoodsInfo['goods_num'] - $ActivityGoodsInfo['buy_num'];

            $row = $ActivityGoodsInfo;
        }
        //是否设置过开抢提醒
        $key = "flash_sale_notice_uid-" . $this->auth->id . '-' .$goods_id;
        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        $exists = $client->hexists($key,'goods_id');
        if($exists){
            //设置过
            $is_qiang = 1;

        }else{
            $is_qiang = 0;

        }
        $row['is_qiang'] = $is_qiang;

        $this->success('', $row);
    }

    /**
     * 设置开抢提醒
     * formid
     * goods_id
     */
    public function addFlashSalenotice(){
        $formId = $this->request->request('formid');
        $goodsId = $this->request->request('goods_id');

        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        //设置开抢提醒的用户集合
        $userIdKeys = 'flash_sale_notice_user_ids';
        $client->sadd($userIdKeys,$this->auth->id);

        //提醒开抢商品
        $goodsIdKey = "flash_sale_notice_goods_id-" . $this->auth->id;
        $client->lrem($goodsIdKey,1,$goodsId);
        $client->rpush($goodsIdKey,$goodsId);

        $key = "flash_sale_notice_uid-" . $this->auth->id . '-' .$goodsId;
        if(!$client->hlen($key)){
            $notice_time = strtotime(date("Y-m-d H",time()).":00:00")-600;
            $value = [
                'formid' => $formId,
                'user_id' => $this->auth->id,
                'goods_id' => $goodsId,
                'notice_time' => $notice_time
            ];
            $client->hmset($key,$value);
        }
        $data = [
            'goodsidlist' => $client->lrange($goodsIdKey,0,-1),
            'goodshashlist' => $client->hgetall($key)
        ];
        $this->success('',$data);
    }

    /**
     * 取消开抢提醒
     */
    public function cancelFlashSalenotice(){
        $goodsId = $this->request->request('goods_id');
        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        //取消开抢提醒的用户集合
        $userIdKeys = 'flash_sale_notice_user_ids';
        $client->srem($userIdKeys,$this->auth->id);

        $key = "flash_sale_notice_uid-" . $this->auth->id . '-' .$goodsId;
        $client->del($key);

        $goodsIdKey = "flash_sale_notice_goods_id-" . $this->auth->id;
        $client->lrem($goodsIdKey,1,$goodsId);


        $data = [
            'goodsidlist' => $client->lrange($goodsIdKey,0,-1),
            'goodshashlist' => $client->hgetall($key)
        ];
        $this->success('',$data);

    }


    /**
     * 定时任务，开抢提醒
     */
    public function autoNotice(){
        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);


        //开抢提醒的用户集合
        $userIdKeys = 'flash_sale_notice_user_ids';
        $users = $client->smembers($userIdKeys);
        $goodshashlist = [];
        foreach($users as $k0 => $v0){
            $goodsIdKey = "flash_sale_notice_goods_id-" . $v0;
            $goodsidlist = $client->lrange($goodsIdKey,0,-1);
            foreach($goodsidlist as $k => $v){
                $key = "flash_sale_notice_uid-" . $v0 . '-' .$v;
                $goodshashlist[$k] = $client->hgetall($key);
            }
        }


        $wx = new \wechat\Wx();
        foreach($goodshashlist as $k => $v){
            if(!empty($v)){
                $startTime = $v['notice_time'] -300;
                $endTime = $v['notice_time']+300;
                if(time()>$startTime && time()< $endTime){
                    $wx->sendWxMsg($v['user_id'],$v['formid'],$v['goods_id']);
                    $key = "flash_sale_notice_uid-" . $v['user_id'] . '-' .$v['goods_id'];
                    $client->del($key);
                    $goodsIdKey = "flash_sale_notice_goods_id-" . $v['goods_id'];
                    $client->lrem($goodsIdKey,1,$v['goods_id']);

                }

            }
        }
    }

}